package com.example.hxpc.guidancemanagement.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.hxpc.guidancemanagement.R;
import com.example.hxpc.guidancemanagement.activity.CreateProjectActivity;
import com.example.hxpc.guidancemanagement.activity.MainActivity;
import com.example.hxpc.guidancemanagement.activity.NumberListActivity;
import com.example.hxpc.guidancemanagement.activity.ProjectDetailActivity;
import com.example.hxpc.guidancemanagement.adapter.MyRecycleViewAdapter;
import com.example.hxpc.guidancemanagement.api.BaseApi;
import com.example.hxpc.guidancemanagement.base.ProjectInfo;
import com.example.hxpc.guidancemanagement.model.JsonBase;
import com.example.hxpc.guidancemanagement.model.JsonFeedback;
import com.example.hxpc.guidancemanagement.tools.LogoutT;
import com.example.hxpc.guidancemanagement.tools.ToastTools;
import com.example.hxpc.guidancemanagement.tools.dataTools.OkHttpTools;
import com.example.hxpc.guidancemanagement.tools.mold.BasePopupWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tao on 2017/11/29.
 * 主页面-项目Frament
 */

public class MainProFragment extends Fragment implements View.OnClickListener ,SwipeRefreshLayout.OnRefreshListener ,BaseApi{
    private ImageView add_img , back_img;
    private View rootView;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<ProjectInfo> mDatas =  new ArrayList<ProjectInfo>();
    private MyRecycleViewAdapter myRecycleViewAdapter;
    private OkHttpTools okHttpTools = new OkHttpTools();
//    private String[] menuInfo = {"创建项目","消息"};
    private String[] menuInfo;
    private int screenHeight;
    private int screenWidth;
    private PopupWindow popupWindow;
    private String name , number , teacher ,state,path;
    private TextView te_is_pro;
    private String type;
    private Intent intent;
    private long refreshTime = 0;//用来记录Fragment刷新的时间
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.frament_main_project,null);
        }
        if (getUserVisibleHint()){
            okHttpTools.getAllProject(this);
            refreshTime = System.currentTimeMillis();
        }
        refreshTime = 0;
        initView(rootView);
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && isVisible()){
            if (refreshTime == 0 || (refreshTime != 0 && (System.currentTimeMillis() - refreshTime)>30*60*1000)){
                okHttpTools.getAllProject(this);
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    //初始化时的判断
    public void isHavePro(){
        if (mDatas.size()==0){
            te_is_pro.setText("当前没有项目，点击右上角创建项目！");
        }else{
            te_is_pro.setText("");
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        type = ((MainActivity)activity).getUserType();
    }

    /**
     * 初始化标题
     * @param rootView
     */
    public void initTitleBar(View rootView){
        TextView te_title = (TextView) rootView.findViewById(R.id.te_title);
        switch (type){
            case "1":
                te_title.setText("管理员");
                menuInfo = new String[]{"成员"};
                break;
            case "2":
                te_title.setText("超级用户");
                menuInfo = new String[]{"创建项目"};
                break;
            case "3":
                te_title.setText("普通用户");
                add_img.setVisibility(View.INVISIBLE);
                break;
            case "4":
                te_title.setText("游客");
                add_img.setVisibility(View.INVISIBLE);
                break;
        }
    }

    //初始化控件
    public void initView(View rootView){
        te_is_pro = (TextView) rootView.findViewById(R.id.te_is_pro);
        add_img = (ImageView) rootView.findViewById(R.id.add_mark);
        add_img.setOnClickListener(this);
        back_img = (ImageView) rootView.findViewById(R.id.back);
        back_img.setVisibility(View.GONE);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.srl_main);
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycleView);
//        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecycleViewAdapter = new MyRecycleViewAdapter(getActivity(),mDatas);
//        myRecycleViewAdapter.addHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_add,null));
        recyclerView.setAdapter(myRecycleViewAdapter);
        myRecycleViewAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
//                ToastTools.toastMsg(getActivity(),"您点击了第"+position+"项");
                Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
                intent.putExtra("projectName",mDatas.get(position).getProjectName());
                intent.putExtra("projectJoinNum",mDatas.get(position).getNumber());
                intent.putExtra("projectState",mDatas.get(position).getState());
                intent.putExtra("projectTeacher",mDatas.get(position).getTeacher());
                LogoutT.logout(mDatas.get(position).getPath()+"   333 3333 ");
                intent.putExtra("projectPath",mDatas.get(position).getPath());
                startActivity(intent);
            }

            @Override
            public void onItemLongOnClick(View view, int position) {
                LogoutT.logout("长按了");
            }
        });
        initTitleBar(rootView);
    }

    public void getPopupWindow(){
        //获取屏幕高度和宽度
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        screenHeight = wm.getDefaultDisplay().getHeight();
        screenWidth = wm.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow,null);
        ListView listView = (ListView) view.findViewById(R.id.popu_listView);
        if(menuInfo != null && menuInfo.length>0){
            listView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,menuInfo));
        }
        popupWindow = new BasePopupWindow(view,screenWidth/4,ViewGroup.LayoutParams.WRAP_CONTENT,true,true,true,true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        popupWindow.setAnimationStyle(R.style.popup_window_anim);
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0){
                    popupWindow.dismiss();
                    if (type.equals("1")){
                        intent = new Intent(getActivity(), NumberListActivity.class);
                        startActivity(intent);
                    }else if (type.equals("2")){
                        intent = new Intent(getActivity(), CreateProjectActivity.class);
                        startActivityForResult(intent,0);
                    }
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1){
            if (requestCode == 0){
                name = data.getStringExtra("name");
                number = data.getStringExtra("number");
                teacher = data.getStringExtra("teacher");
                state = data.getStringExtra("state");
                path = data.getStringExtra("path");
                LogoutT.logout(name + number + teacher + state+path);
                initData(name , number ,teacher ,state,path);
                myRecycleViewAdapter.notifyDataSetChanged();
                isHavePro();
            }
        }
    }

    //添加项目
    private void initData(String name , String number , String teacher , String state,String path){
        ProjectInfo pro = new ProjectInfo(name , number , teacher , state,path);
        mDatas.add(pro);
    }

    @Override
    public void onClick(View v) {
        getPopupWindow();
        popupWindow.showAtLocation(getActivity().getLayoutInflater().inflate(R.layout.frament_main_project, null),0,
                470, 90);//430 140
        backgroundAlpha(0.7f);
    }

    //改变背景颜色
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }

    @Override
    public void onRefresh() {
        //实际项目中这里一般是用网络请求获取数据
        LogoutT.logout("llllll  ttt");
        okHttpTools.getAllProject(this);
        myRecycleViewAdapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void backMsg(String success, JsonBase jsonBase) {

    }

    @Override
    public void backMsg(String success, JsonFeedback jsonFeedback) {
        if (success.equals("true")){
            mDatas.clear();
            for(int i = 0 ;i<jsonFeedback.getData().size(); i++){
                ProjectInfo pf = new ProjectInfo();
//                LogoutT.logout(jsonFeedback.getData().get(i).getProjectName());
                pf.setProjectName(jsonFeedback.getData().get(i).getProjectName());
                pf.setNumber(jsonFeedback.getData().get(i).getJoin_num());
                pf.setTeacher(jsonFeedback.getData().get(i).getTeacher());
                pf.setState(jsonFeedback.getData().get(i).getState());
                pf.setPath(jsonFeedback.getData().get(i).getPath());
                mDatas.add(pf);
            }
        }else {
            ToastTools.toastMsg(getActivity(),jsonFeedback.getMsg());
        }
        isHavePro();
    }
}
